#include "../include/threadPool.h"

int exitPipe[2]; // 进程通信管道
void handler(int signum) {
    printf("signum = %d\n", signum);
    write(exitPipe[1], "1", 1);
}

/* Usage:  线程池 -服务端  */
int main(int argc, char *argv[]){

    pipe(exitPipe);
    if (fork()) {
        // 父进程
        close(exitPipe[0]);
        signal(SIGUSR1, handler);
        wait(NULL);
        printf("Server is going to exit!\n");
        exit(0);
    }
    // 子进程 线程池
    close(exitPipe[1]);
    // ../conf/server.conf
    ARGS_CHECK(argc, 2);
    char ip[20] = {0};
    char port[10] = {0};
    int workernum = 0;
    getServerConf(argv[1], ip, port, &workernum);
    printf("server ip: %s\n", ip);
    printf("server port: %s\n", port);
    printf("thread num: %d\n", workernum);

    threadPool_t threadPool;
    // 初始化
    threadPoolInit(&threadPool, workernum);
    // 创建线程池
    makeWorker(&threadPool, workernum);
    // 网络
    int sockfd = initTCP(ip, port);
    int epfd = epoll_create(10);
    epollAdd(epfd, sockfd);
    epollAdd(epfd, exitPipe[0]);

    struct epoll_event readySet[1024] = {0};
    while (1) {
        int readynum = epoll_wait(epfd, readySet, 1024, -1);
        for (int i = 0; i < readynum; i++) {
            if (readySet[i].data.fd == sockfd) {
                int netfd = accept(sockfd, NULL, NULL);
                printf("sockfd = %d, netfd = %d\n", sockfd, netfd);
                // 加锁生产
                pthread_mutex_lock(&threadPool.mutex);
                enQueue(&threadPool.taskQueue, netfd);
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
                // 不能在这里关netfd，交给worker关
            }
            else if (readySet[i].data.fd == exitPipe[0]) {
                printf("ThreadPool is going to exit!\n");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);

                for(int j = 0; j < workernum; ++j){
                    pthread_join(threadPool.tidArr.arr[j], NULL);
                }
                printf("Master is going to exit!\n");
                exit(0);
            }
        }
    }

    pause();
    return 0;
}

